package com.ego.upload.service.impl;

import com.ego.exception.enums.ExceptionEnum;
import com.ego.exception.exception.EgoException;
import com.ego.upload.service.UploadService;
import com.github.tobato.fastdfs.domain.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;

@Service
@Slf4j
public class UploadServiceImpl implements UploadService {

    @Autowired
    private FastFileStorageClient storageClient;

    private List<String> list = Arrays.asList("jpg","png","jpeg");

    @Override
    public String upload(MultipartFile file) {
        String url = null;
        try {
            //校验文件类型
            String ext = StringUtils.substringAfterLast(file.getOriginalFilename(),".");//获取后缀
            if (!list.contains(ext)) {
                EgoException.error(log, ExceptionEnum.INVALID_FILE_FORMAT);
                return null;
            }
            //保存图片

            File dir = new File("D://images");
            if (!dir.exists()) {
                dir.mkdirs();
            }
//            String fileName = UUID.randomUUID().toString()+"."+ext;
//            file.transferTo(new File(dir,fileName));
            StorePath storePath = storageClient.uploadFile(file.getInputStream(), file.getSize(), ext, null);
            //拼接图片地址
            url = "http://image.ego.com/"+storePath.getFullPath();

        }catch (Exception e){
            EgoException.error(log, ExceptionEnum.UPLOAD_IMAGE_EXCEPTION,e);
        }
        return url;
    }
}
